package com.example.presentation_libary;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * FloatTool.java:应用悬浮窗权限请求
 * <p>
 * AndroidMainifest.xml中添加： <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 * <p>
 * 用法：
 * 1、请求悬浮窗权限：FloatTool.RequestOverlayPermission(this);
 * 2、处理悬浮窗权限请求结果：FloatTool.onActivityResult(requestCode, resultCode, data, this);
 */
public class FloatTool {
    public static boolean CanShowFloat = false;

    private static final int REQUEST_OVERLAY = 5004;

    /**
     * 动态请求悬浮窗权限
     */
    public static void RequestOverlayPermission(Activity activity) {
        if (checkFloatPermission(activity)) {
            CanShowFloat = true;
            return;
        }
        // 若当前未允许显示悬浮窗，则提示授权
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= Build.VERSION_CODES.O) {//8.0以上
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            activity.startActivityForResult(intent, REQUEST_OVERLAY);
        } else if (sdkInt >= Build.VERSION_CODES.M) {//6.0-8.0
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivityForResult(intent, REQUEST_OVERLAY);
        } else {//4.4-6.0以下
            //无需处理了
            CanShowFloat = true;
        }

    }

    /**
     * 浮窗权限请求，Activity执行结果，回调函数
     */

    public static void onActivityResult(int requestCode, int resultCode, Intent data, final Activity activity) {
        if (requestCode == REQUEST_OVERLAY)        // 从应用权限设置界面返回
        {
            if (checkFloatPermission(activity)) {
                CanShowFloat = true;        // 设置标识为可显示悬浮窗
            } else {
                CanShowFloat = false;
                // 若当前未允许显示悬浮窗，则提示授权
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setCancelable(false);
                builder.setTitle("悬浮窗权限未授权");
                builder.setMessage("应用需要悬浮窗权限，以展示浮标");
                builder.setPositiveButton("去添加 权限", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        RequestOverlayPermission(activity);
                    }
                });

                builder.setNegativeButton("拒绝则 退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        // 若拒绝了所需的权限请求，则退出应用
                        activity.finish();
                        System.exit(0);
                    }
                });
                builder.show();
            }
        }
    }

    //判断是否开启悬浮窗权限   context可以用你的Activity.或者tiis
    public static boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                if (appOpsMgr == null)
                    return false;
                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
                        .getPackageName());
                return mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED;
            } else {
                return Settings.canDrawOverlays(context);
            }
        }
    }
}